import config from '../../config';
import utils from '../../utils/util';
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    chatList: {
      type: Array,
      value: []
    },
    jiguangUserName: {
      type: Number,
      optionalTypes: [String],
      value: 0,
    },
    chatRoomId: {
      value: "",
      type: Number,
      optionalTypes: [String],
    },
    socialRoomId: {
      type: Number,
      optionalTypes: [String],
      default: 0
    },
    detailId:{
      type: Number,
      optionalTypes: [String],
      default: 0
    },
    isTeachingMode: {
      type: Boolean,
      value: false
    },
    
  },

  /**
   * 组件的初始数据
   */
  data: {
    aspectAudioDuration: 60, //音频基准长度
    aspectAudioWidth: 280, //单位rpx
    audioPlayItem: {}, //
    relationTypeMap: config.relationTypeMap,
    prodMapType: config.prodMapType,
    prodCourseType: config.prodCourseType,
    sourceMapType: {
      31: "视频",
      32: "音频",
      33: "图文",
      34: "专栏",
      35: "测评",
      36: "活动",
      37: "打卡"
    },
    isIos:false,
  },

  lifetimes: {
    created: function () {
      //创建音频对象
    },
    attached: function () {
      this._createInnerAudioCtx();
      this.setData({
        isIos:utils.isIos()
      })
    },
    ready: function () {

    },
    detached: function () {

    },
    error: function (error) {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    _createInnerAudioCtx() {
      this._audioCtx = wx.createInnerAudioContext({
        useWebAudioImplement: false
      });
      this._audioCtx.autoPlay = true;
      this._audioCtx.onPlay(() => {
        console.log('onPlay');
        this.setData({
          'audioPlayItem.status': 2
        });
        this.triggerEvent("audioPlay", {
          from: this.data.isTeachingMode ? 2 : 1
        })
      })
      this._audioCtx.onPause(() => {
        console.log('onPause');
        this.setData({
          'audioPlayItem.status': 3
        })
      })
      this._audioCtx.onError((res) => {
        console.log("onError", res);
        this.setData({
          'audioPlayItem.status': 0
        })
      });
      this._audioCtx.onCanplay(() => {
        console.log("onCanplay", this._audioCtx.autoPlay, this._audioCtx.paused)
        if (this._audioCtx.autoPlay) {
          this._audioCtx.play();
        }
        this.setData({
          'audioPlayItem.status': 2
        })
      });
      this._audioCtx.onWaiting((res) => {
        console.log("onWaiting", res);
        this.setData({
          'audioPlayItem.status': 1
        });
      })
      this._audioCtx.onTimeUpdate(() => {
        // console.log("onTimeUpdate",this.data.audioPlayItem);
        let progressWidth = this.data.audioPlayItem.totalWidth * (this._audioCtx.currentTime / this._audioCtx.duration)
        this.setData({
          'audioPlayItem.playprogressWidth': progressWidth
        })

      })
      this._audioCtx.onEnded((res) => {
        console.log("onEnded", res);
        this.setData({
          'audioPlayItem.status': 0,
          'audioPlayItem.playprogressWidth': 0
        })
      })
    },
    audioTogglePlay(e) {
      let item = e.currentTarget.dataset.item;
      if (this.data.audioPlayItem.socialRoomMessageId != item.socialRoomMessageId) {
        let querySelector = this.createSelectorQuery();
        querySelector.select('#timeline-' + item.socialRoomMessageId).boundingClientRect();
        querySelector.exec((res) => {
          console.log(res);
          this.setData({
            audioPlayItem: {
              socialRoomMessageId: item.socialRoomMessageId,
              playprogressWidth: 0,
              totalWidth: res[0].width,
              status: 0, //0初始状态 1加载中 2播放中 3暂停
            }
          }, () => {
            this._audioCtx.src = item.content;
          });
        });
      } else {
        if (this._audioCtx.paused) {
          this._audioCtx.play();
        } else {
          this._audioCtx.pause();
        }
      }
    },
    audioPlay(e){
      let item = e.currentTarget.dataset.item;
      if (this.data.audioPlayItem.socialRoomMessageId != item.socialRoomMessageId) {
        this._audioCtx.pause();
        let querySelector = this.createSelectorQuery();
        querySelector.select('#timeline-' + item.socialRoomMessageId).boundingClientRect();
        querySelector.exec((res) => {
          console.log(res);
          this.setData({
            audioPlayItem: {
              socialRoomMessageId: item.socialRoomMessageId,
              playprogressWidth: 0,
              totalWidth: res[0].width,
              status: 1, //0初始状态 1加载中 2播放中 3暂停
            }
          }, () => {
            this._audioCtx.src = item.content;
          });
        });
      }else{
        this._audioCtx.play();
      } 
    },
    //对外暴露暂停的接口
    audioPause() {
      this._audioCtx && this._audioCtx.pause();
    },
    previewImg(e) {
      console.log(e)
      wx.previewImage({
        current: e.currentTarget.dataset.src, // 当前显示图片的http链接
        urls: [e.currentTarget.dataset.src] // 需要预览的图片http链接列表
      })
    },
    switchBuyGuide(e){
      let data = e.currentTarget.dataset.item;
      this.triggerEvent("switchBuyGuide",data)
    },
    openCouponBuyGuide(){
      wx.showToast({
        title: '小程序暂不支持购买',
        icon:"none"
      })
    },
    getCoupon(e) {
      let info =e.currentTarget.dataset.item; 
      if (this._isRequesting) return;
      utils.getBindPhoneSetting(config.ckFrom.coupon).then((res) => {
        if (res.getBind) {
          wx.showToast({
            title: '请绑定手机号码',
          });
          this.triggerEvent("bindPhone")
          this._isRequesting = false;
        } else {
            let url = '',
            data = {
              source: 13,
              SocialRoomId: this.data.socialRoomId
            };
          if(this.data.detailId){
            data.detailId = this.data.detailId;
          }
          if (info.prodType == 200) {
            url = `coupon/collectJWCoupon`;
            data.redeemCodeId = info.relationId;
          } else {
            url = `redeemCodes/collectRedeemCode/${info.relationId}`;
          }
          utils.post(url, data).then(res => {
            this._isRequesting = false;
            if (res.status == 1) {
              wx.showToast({
                title: '领取成功，请在“个人中心>优惠券”中查看',
                icon: "none"
              })
            } else {
              wx.showToast({
                title: res.detail ? res.detail : res.msg,
                icon: "none"
              })
            }
            this.onClose();
          }).catch(() => {
            this._isRequesting = false;
          })
        }
      }).catch(() => {
        this._isRequesting = false;
      })
    },
  }
})